package com.example.yiwei.crm.view.activity.menuActivity;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;

import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.BaseActivity;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.personalDao;
import com.example.yiwei.crm.dao_impl.personalDaoImpl;
import com.example.yiwei.crm.data.GetPersonnal;
import com.example.yiwei.crm.data.QXData;
import com.example.yiwei.crm.entity.VersionEntity;
import com.example.yiwei.crm.entity.personnalEntity;
import com.example.yiwei.crm.json.QXjson;
import com.example.yiwei.crm.json.VersionJson;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.util.SC;
import com.example.yiwei.crm.view.activity.coordinationActivity.UpdatePasswordActivity;
import com.example.yiwei.crm.view.activity.jdjycooractivity.JDJYCoorActivity;
import com.example.yiwei.crm.view.activity.jtCustomer.JDcoorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

//登录界面
public class LoginActivity extends BaseActivity {
    EditText edit_account,edit_password;
    com.example.yiwei.crm.entity.personnalEntity personnalEntity;
    String result;
    String username;
    String BOOLEAN;
    String password;
    String username1;
    String password1;
    String str;
    SharedPreferences sp1;
    SharedPreferences sp;
    String version;
    VersionEntity versionEntity;
    AlertDialog.Builder builder2;
    static LoginActivity a;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        a= this;
        edit_account = (EditText) findViewById(R.id.main_edit_accounts);
        edit_password = (EditText) findViewById(R.id.main_edit_password);
        sp1 = getSharedPreferences("login", Context.MODE_PRIVATE);
        username1 = sp1.getString("username", null);
        password1 = sp1.getString("password", null);
        edit_account.setText(username1);
//        edit_password.setText(password1);
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                SC sc = new SC();
//                JSONObject object = sc.storage(sp1);
//                try {
//                    object.put("KAA02","明天");
//                    object.put("KGA04B","2017-6-5");
//                    object.put("KGA04E","2017-6-9");
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//                String json = object.toString();
//                String count = NetWorkUtils.getCount("http://172.16.40.21:8080/YWCRM/APPKAA1JIA/listjiaPageKga1", json);
//                Log.d("aaa",count);
//            }
//        }).start();
        if ("exit".equals(getIntent().getStringExtra("tag"))) {

        } else {
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    personnalEntity = new personnalEntity();
//                    personalDao personalDao = new personalDaoImpl();
//                    GetPersonnal.create();
//                    personnalEntity = personalDao.queryPersonnalMessage(baseClass.query_mine_message, null);
//                    GetPersonnal.personnalEntity = personnalEntity;
//                    if (username1 != null && password1 != null) {
////                        Intent intent=new Intent(LoginActivity.this,LoginActivity2.class);
////                        startActivity(intent);
////                        finish();
//                    }
//                }
//            }).start();

        }
    }

    public void onClick(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject json=new JSONObject();
                try {
                    json.put("KEYDATA",edit_account.getText().toString()+","+edit_password.getText().toString());

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String sjson = json.toString();
                    result= NetWorkUtils.getCount(baseClass.log_URL,sjson);
                try {
                    JSONObject object=new JSONObject(result);
                    String BOOLEAN=object.getString("result");
                    if (object.has("username")){
                        username = object.getString("username");
                    }
                    if (object.has("password")){
                        password = object.getString("password");
                    }

                    JSONObject user = (JSONObject) object.get("pd");
                   str = object.getString("result");
                    sp = getSharedPreferences("login", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("username",edit_account.getText().toString());
                    editor.putString("password",edit_password.getText().toString());
                    //当前用户的主键
                    if (user.has("UAB01")){
                        editor.putString("CID01",  user.getString("UAB01"));
                        editor.putString("UAB01", user.getString("UAB01"));
                    }
                    //当前用户的编码
                    if (user.has("UAC02")){
                        editor.putString("CID02",  user.getString("UAC02"));
                        editor.putString("UAC02", user.getString("UAC02"));
                    }
                    //当前用户的姓名
                    if (user.has("UAB03")){
                        editor.putString("CID03",  user.getString("UAB03"));
                        editor.putString("UAB03", user.getString("UAB03"));
                    }
                    if (object.has("admin")){
                        editor.putString("admin",object.getString("admin"));
                    }

                    if (user.has("UAB01")){
                        editor.putString("UID01",  user.getString("UAB01"));
                    }
                    if (user.has("UAB02")){
                        editor.putString("UAB02",  user.getString("UAB02"));
                    }
                    if (user.has("UAC03")){
                        editor.putString("UAC03",  user.getString("UAC03"));
                    }
                    if (user.has("UAC02")){
                        editor.putString("UID02",  user.getString("UAC02"));
                    }
                    //用户的用户表主键
                    if (user.has("UAC01")){
                        editor.putString("UAC01",  user.getString("UAC01"));
                    }
                    if (user.has("UAB03")){
                        editor.putString("UID03",  user.getString("UAB03"));
                    }
                    //当前医疗机构ID
                    if (user.has("UAA01")){
                        editor.putString("UNT01",  user.getString("UAA01"));
                        editor.putString("UAA01",  user.getString("UAA01"));
                    }
                    //当前医疗机构编码
                    if (user.has("UAA02")){
                        editor.putString("UNT02",  user.getString("UAA02"));
                        editor.putString("UAA02",  user.getString("UAA02"));
                    }
                    if (user.has("UAC05")){
                        editor.putString("UAC05",  user.getString("UAC05"));
                    }
                    if (user.has("UAB06")){
                        editor.putString("UAB06",  user.getString("UAB06"));
                    }
                    //当前医疗机构的名字
                    if (user.has("UAA03")){
                        editor.putString("UNT03",  user.getString("UAA03"));
                        editor.putString("UAA03",  user.getString("UAA03"));
                    }

                    if (user.has("depts")){
                        editor.putString("DEPTS",user.getString("depts"));
                    }else{
                        editor.putString("DEPTS",null);
                    }
                    if ("success".equals(BOOLEAN)){
                        editor.commit();
                        SC sc = new SC();
                        JSONObject object1 = sc.storage(sp);
                        String json1 = object1.toString();
                        String result= NetWorkUtils.getCount(baseClass.find_qx_URL,json1);
                        QXData.creat();
                        QXData.list = QXjson.get(result);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (QXData.list!=null){
                                    final String UAB06  = sp.getString("UAB06",null);
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            JSONObject object2 = new JSONObject();
                                            try {
                                                object2.put("APP03",2);
                                                object2.put("APP04",2);
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            String json = object2.toString();
                                            String result = NetWorkUtils.getCount(baseClass.get_Vresion_URL,json);
                                            Log.d("result = ",result);
                                            versionEntity = VersionJson.getVersion(result);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    String str1 = null;
                                                    try {
                                                        str1 = getVersionName();
                                                        double a = Double.valueOf(str1);
                                                        double b = Double.valueOf(versionEntity.getVersionname());
                                                        Log.d("cccccc",a+"   "+b);
                                                        if (a<b){
                                                            showandDownLoad();

                                                        }else  if("000000".equals(edit_password.getText().toString())){
                                                            Intent intent = new Intent(LoginActivity.this, UpdatePasswordActivity.class);
                                                            intent.putExtra("login","login");
                                                            startActivity(intent);
                                                            finish();
                                                        }else if ("20".equals(UAB06)||"21".equals(UAB06)){
                                                            Intent intent=new Intent(LoginActivity.this,JDcoorActivity.class);
                                                            startActivity(intent);
                                                            finish();
                                                        }else if ("22".equals(UAB06)){
                                                            Intent intent=new Intent(LoginActivity.this,JDJYCoorActivity.class);
                                                            startActivity(intent);
                                                            finish();
                                                        }else {
                                                            Toast.makeText(LoginActivity.this, "帐号不能登录！", Toast.LENGTH_SHORT).show();
                                                        }
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            });
                                        }
                                    }).start();



                                }
                            }
                        });


                    }else if("usererror".equals(str)){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                            }
                        });

                    }else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    if("usererror".equals(str)){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                            }
                        });

                    }else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
        }).start();
    }
//    public boolean isNetworkAvailable(Context context)
//    {
//        if (context != null) {
//            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
//                    .getSystemService(Context.CONNECTIVITY_SERVICE);
//            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
//            if (mNetworkInfo != null) {
//                return mNetworkInfo.isAvailable();
//            }
//        }
//        return false;
//    }

    public String getVersionName() throws Exception
    {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
        String version = packInfo.versionName;
        return version;
    }
    public void showandDownLoad(){
        AlertDialog.Builder builder;
        builder = new AlertDialog.Builder(new ContextThemeWrapper(LoginActivity.this, R.style.custom_dialog));
        builder.setTitle("有新版本来");
        builder2 = new AlertDialog.Builder(new ContextThemeWrapper(LoginActivity.this, R.style.custom_dialog));
        builder2.setTitle("文件正在下载，请稍后");
        builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        File file = new File(Environment.getExternalStorageDirectory() + "/CRM/crm.txt");
//                        final String result = HttpAssist.uploadFile(file,versionEntity.getDownloadURL());
                        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionEntity.getDownloadURL()));
                        //设置在什么网络情况下进行下载
                        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
                        //设置通知栏标题
                        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
                        request.setTitle("crm.apk");
                        request.setDescription("CRM正在下载");
                        request.setAllowedOverRoaming(false);
                        //设置文件存放目录
                        File folder = new File(Environment.getExternalStorageDirectory()+"/CRM");
                        if (folder.exists()){
                            File file = new File(Environment.getExternalStorageDirectory()+"/CRM/crm.apk");
                            if (file.exists()){
                                file.delete();
                            }
                        }else {
                            folder.mkdirs();
                        }
                        request.setDestinationInExternalPublicDir("CRM","crm.apk");
                        DownloadManager downManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                        long id = downManager.enqueue(request);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                builder2.setCancelable(false);
                                builder2.show();
                            }
                        });
                    }
                }).start();
            }
        });
        builder.setCancelable(false);
        builder.show();
    }
    public static class DownLoadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//                Log.d("aaaa","cccc");
                File apkfile = new File(Environment.getExternalStorageDirectory()+"/CRM/crm.apk");
                if (!apkfile.exists()) {
                    return;
                }
                // 通过Intent安装APK文件
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                        "application/vnd.android.package-archive");
                LoginActivity.a.startActivity(i);
                android.os.Process.killProcess(android.os.Process.myPid());

            }
        }

    }

}
